import 'package:erp_widget/src/components/picker/base/picker_clip_rrect.dart';
import 'package:erp_widget/src/components/picker/base/picker_title.dart';
import 'package:erp_widget/erp_widget.dart';
import 'package:flutter/material.dart';

/// 点击确定时的回调
/// [selectedItems] 被选中的 item 集合
///
/// 事件拦截回调（如果配置了此项，返回值为是否拦截，如果为true，则进行拦截，不进行默认回调）
typedef DxRadioListClickInterceptor = bool Function(List<DxPickerItem> selectedItems);
typedef DxRadioListPickerConfirm = void Function(List<DxPickerItem> selectedItems);

/// 多选列表 Picker
class DxRadioListPicker<T> extends StatefulWidget {
  /// 标题
  final String title;

  final Future<T>? future;

  /// 数据条目
  final List<DxPickerItem>? items;

  /// 最多选择多少个item，默认可以无限选
  final int maxSelectCount;

  /// 拦截器
  final DxRadioListClickInterceptor? interceptor;

  /// 确定事件
  final DxRadioListPickerConfirm? onConfirm;

  /// 主题
  final DxPickerThemeData? themeData;

  static void show<T>(
    BuildContext context, {
    String title = '请选择',
    Future<T>? future,
    List<DxPickerItem>? items,
    int maxSelectCount = 0,
    DxRadioListClickInterceptor? interceptor,
    DxRadioListPickerConfirm? onConfirm,
    DxPickerThemeData? themeData,
  }) {
    if (future == null && items == null) {
      throw 'future or items can\'t be empty at the same time';
    }
    themeData = DxPickerThemeData().merge(themeData);
    showModalBottomSheet(
      context: context,
      isDismissible: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext dialogContext) {
        return DxRadioListPicker(
          title: title,
          future: future,
          items: items,
          maxSelectCount: maxSelectCount,
          interceptor: interceptor,
          onConfirm: onConfirm,
          themeData: themeData,
        );
      },
    );
  }

  const DxRadioListPicker({
    Key? key,
    this.title = '请选择',
    this.future,
    this.items,
    this.maxSelectCount = 0,
    this.interceptor,
    this.onConfirm,
    this.themeData,
  }) : super(key: key);

  @override
  State<DxRadioListPicker> createState() => _DxRadioListPickerState();
}

class _DxRadioListPickerState extends State<DxRadioListPicker> {
  List<DxPickerItem> dataList = [];

  List<DxPickerItem> get _selectedList {
    return dataList.where((element) => element.isSelect).toList();
  }

  @override
  void initState() {
    super.initState();
    dataList = widget.items ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return DxPickerClipRRect(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(widget.themeData?.cornerRadius ?? 5),
        topRight: Radius.circular(widget.themeData?.cornerRadius ?? 5),
      ),
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.only(bottom: 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            DxPickerTitle(
              pickerTitleConfig: DxPickerTitleConfig(titleText: widget.title),
              onConfirm: () {
                if (widget.interceptor == null || !widget.interceptor!(_selectedList)) {
                  widget.onConfirm?.call(_selectedList);
                  Navigator.of(context).pop();
                }
              },
              onCancel: () => Navigator.of(context).pop(),
            ),
            SizedBox(
              width: double.infinity,
              height: widget.themeData?.pickerHeight,
              child: ScrollConfiguration(
                behavior: DxNoScrollBehavior(),
                child: _buildChild(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构造子组件
  Widget _buildChild() {
    if (widget.future != null) {
      return DxFutureBuilder(
        future: widget.future!,
        onLoading: () => Center(
          child: DxLoading(
            height: 28,
            type: DxLoadingType.lineScalePulseOutRapid,
            colors: DxStyle.gradientRainbow,
          ),
        ),
        onDone: (dynamic snapshotData) {
          dataList = snapshotData as List<DxPickerItem>;
          return ListView.builder(
            shrinkWrap: true,
            physics: const BouncingScrollPhysics(),
            itemBuilder: (context, index) => _buildItem(context, index),
            itemCount: dataList.length,
          );
        },
      );
    }
    return ListView.builder(
      shrinkWrap: true,
      physics: const BouncingScrollPhysics(),
      itemBuilder: (context, index) => _buildItem(context, index),
      itemCount: dataList.length,
    );
  }

  /// 选中数据
  void initDataList() {
    for (DxPickerItem item in dataList) {
      //选中的按钮
      if (item.isSelect == true) {
        _selectedList.add(item);
      }
    }
  }

  Widget _buildItem(BuildContext context, int index) {
    /// 获取当前的选中状态
    DxPickerItem pickerItem = dataList[index];
    bool selectStatus = pickerItem.isSelect;
    Widget current = pickerItem.subTitle == null
        ? Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        pickerItem.name,
                        style: selectStatus ? widget.themeData?.tagSelectedTextStyle : widget.themeData?.tagTextStyle,
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      height: 50,
                      child: selectStatus
                          ? Image.asset(DxAsset.selected, scale: 3.0, package: 'erp_widget')
                          : Image.asset(DxAsset.unSelected, scale: 3.0, package: 'erp_widget'),
                    ),
                  ],
                ),
              ),
              index != dataList.length - 1
                  ? const Padding(padding: EdgeInsets.fromLTRB(20, 0, 20, 0), child: DxDivider())
                  : const SizedBox.shrink()
            ],
          )
        : DxListTile(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
            borderPosition:
                index != dataList.length - 1 ? DxListTileBorderPosition.bottom : DxListTileBorderPosition.none,
            titleWidget: Text(
              pickerItem.name,
              style: selectStatus ? widget.themeData?.tagSelectedTextStyle : widget.themeData?.tagTextStyle,
            ),
            subTitleWidget: Text(pickerItem.subTitle!, style: selectStatus ? DxStyle.$3E7AF5$11 : DxStyle.$999999$11),
            trailing: selectStatus
                ? Image.asset(DxAsset.selected, scale: 3.0, package: 'erp_widget')
                : Image.asset(DxAsset.unSelected, scale: 3.0, package: 'erp_widget'),
          );
    return pickerItem.isDisabled
        ? Opacity(opacity: DxStyle.disabledOpacity, child: current)
        : GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              if (widget.maxSelectCount == 1) {
                for (var item in dataList) {
                  item.isSelect = false;
                }
                setState(() {
                  dataList[index].isSelect = !dataList[index].isSelect;
                });
                // _selectedList.clear();
                // if (!selectStatus) {
                //   _selectedList.add(dataList[index]);
                // }
                return;
              }
              if (widget.maxSelectCount > 0 && _selectedList.length >= widget.maxSelectCount && selectStatus == false) {
                DxToast.show('最多选择${widget.maxSelectCount}个');
                return;
              }
              setState(() {
                dataList[index].isSelect = !dataList[index].isSelect;
              });
              // if (!selectStatus) {
              //   _selectedList.add(dataList[index]);
              // } else {
              //   _selectedList.remove(dataList[index]);
              // }
            },
            child: current,
          );
  }
}
